//
//  LZScanQRCodeViewController.m
//  LZQRCode
//
//  Created by apple on 16/4/20.
//  Copyright © 2016年 m14a.cn. All rights reserved.
//

#import "LZScanQRCodeViewController.h"
#import <AVFoundation/AVFoundation.h>

@interface LZScanQRCodeViewController () <AVCaptureMetadataOutputObjectsDelegate>

/** 会话 */
@property (nonatomic ,strong)  AVCaptureSession *session;

/** 图层*/
@property (nonatomic ,weak) AVCaptureVideoPreviewLayer *layer;

@end

@implementation LZScanQRCodeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    // 1. 获取摄像头设备
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    
    // 2. 把摄像头设备设置为输入设备
    AVCaptureDeviceInput *input = [[AVCaptureDeviceInput alloc] initWithDevice:device error:nil];
    
    
    // 3. 创建元数据输出处理对象(元数据, "中间数据")
    AVCaptureMetadataOutput *output = [[AVCaptureMetadataOutput alloc] init];
    // 3.1 设置元数据处理对象, 接收结果的对象
    [output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    
    
    // 4. 创建会话, 连接输入和输出
    AVCaptureSession *session = [[AVCaptureSession alloc] init];
    self.session = session;
    [session addInput:input];
    [session addOutput:output];
    
    // 4.1 设置元数据处理的字符格式(编码格式)(一定要放在会话添加输出处理源之后 , 否则会直接崩溃)
    [output setMetadataObjectTypes:@[AVMetadataObjectTypeQRCode]];
    
    
    // 4.2 添加视频预览图层
    AVCaptureVideoPreviewLayer *layer = [AVCaptureVideoPreviewLayer layerWithSession:session];
    self.layer = layer;
    layer.frame = self.view.bounds;
    [self.view.layer addSublayer:layer];
    
    // 5. 启动会话
    [session startRunning];
}

#pragma mark - AVCaptureMetadataOutputObjectsDelegate
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
    
    if (metadataObjects.count > 0) {
        AVMetadataMachineReadableCodeObject *object = [metadataObjects lastObject];
        NSLog(@"%@", object.stringValue);
        [self.session stopRunning];
        [self.layer removeFromSuperlayer];
        
    }
}

@end
